package com.zwzc.util;


import com.zwzc.BusConstant;
import com.zwzc.module.sys.entity.SysUser;
import com.zwzc.sys.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: UserUtil
 * @Description: 用户工具类
 */
@Component
public class UserUtil {
    @Autowired
    private SysUserFeign feign;
    @Autowired
    private static SysUserFeign sysUserFeign;

    @PostConstruct
    public void init() {
        UserUtil.sysUserFeign = feign;
    }


    /**
     * 获取 request 里传递的 token
     *
     * @param request
     * @return
     */
    public static String getTokenByRequest(HttpServletRequest request) {
        String token = request.getParameter(BusConstant.TOKEN);
        if (token == null) {
            token = request.getHeader(BusConstant.X_ACCESS_TOKEN);
        }

        return token;
    }

    /*
     * @Author hejialun
     * @Description: TODO(获取用户名)
     * @date 2021/5/14 20:30
     * @return
     */
    public static String getUserName() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String username = JwtUtils.getKey(getTokenByRequest(request), "username");
        return username;
    }

    /*
     * @Author hejialun
     * @Description: TODO(获取用户信息)
     * @date 2021/5/14 20:30
     * @return
     */
    public static SysUser getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String username = JwtUtils.getKey(getTokenByRequest(request), "username");
        SysUser user = sysUserFeign.getUserInfoByUsername(username).getData();
        return user;
    }


    /*
     * @Author hejialun
     * @Description: TODO(获取用户id)
     * @date 2021/5/14 20:30
     * @return
     */
    public static String getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return JwtUtils.getKey(getTokenByRequest(request), "id");
    }


}